package com.base.util.javautils.observer;

import android.support.annotation.NonNull;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by gj on 16-1-27.
 */
public class ObservableForThread extends ObservableForMainThread {

    private final Map<Long, Boolean> mCanNextNotifyMap = new ConcurrentHashMap<>();

    @Override
    public synchronized void deleteObservers() {
        super.deleteObservers();
    }

    @Override
    public void notifyObservers(@NonNull AbstractObserverMessage data) {

        Long tid = Thread.currentThread().getId();
        mCanNextNotifyMap.put(tid, Boolean.TRUE);

        IObserver[] array = null;

        synchronized (this) {
            if (mObservers.size() > 0) {
                array = (IObserver[]) mObservers.toArray();
            }
        }

        if (array != null) {
            for (int i = 0; i < array.length; ++i) {
                if (mCanNextNotifyMap.get(tid)) {
                    array[i].update(this, data);
                }
            }
        }

        mCanNextNotifyMap.put(tid, Boolean.FALSE);
    }

    @Override
    public synchronized void registerObserver(@NonNull IObserver observer) {
        super.registerObserver(observer);
    }

    @Override
    public synchronized void unregisterObserver(@NonNull IObserver observer) {
        super.unregisterObserver(observer);
    }

    @Override
    public void cancelNextNotify() {
        Long tid = Thread.currentThread().getId();
        mCanNextNotifyMap.put(tid, Boolean.FALSE);
    }

}
